package org.jugile.util;

/*

Copyright (C) 2007-2011 Jukka Rahkonen  email: jukka.rahkonen@iki.fi

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

*/

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * ""
 * 
 * @author jukka.rahkonen@iki.fi
 */
public class U {

	// ----- strings -----

	public static boolean empty(String str) {
		if (str == null || str.trim().length() == 0) return true;
		return false;
	}
	
	// ----- fail & log -----
	
	public static void fail(String msg) {
		throw new RuntimeException(msg);
	}
	
	public static void fail(Exception e) {
		throw new RuntimeException(e);
	}
	
	public static void log(String msg) {
		System.out.println(msg);
	}
	public static void log(Exception e, String msg) {
		System.out.println(e.toString() + "\n" + msg);
	}

	public static void print(String msg) {
		System.out.println(msg);
	}

	
	// ----- now -----
	
	private static Date now = null;
	public static Date now() {
		if (now == null) return new Date();
		return now;
	}
	
	public static void setNow(String str) {
		now = sdf(str, "dd.MM.yyyy HH:mm");
	}
	public static void addNow(int hours) {
		if (now == null) return;
		now = new Date(now.getTime() + hours*60*60*1000L);
	}
	
	
	// ----- sdf -----
	
	public static Date sdf(String str) {
		if (empty(str)) return null;
		if (str.length() > 10) return sdf(str,"dd.MM.yyyy HH:mm");
		return sdf(str,"dd.MM.yyyy");
	}
	public static Date sdf(String str, String fmt) {
		SimpleDateFormat sdf = new SimpleDateFormat(fmt);
		try {
			return sdf.parse(str);
		} catch (ParseException e) { }
		fail("invalid date: " + str + " with format: " + fmt);
		return null; // not reached
	}
	public static Date sdfSafe(String str, String fmt) {
		SimpleDateFormat sdf = new SimpleDateFormat(fmt);
		try { return sdf.parse(str); } catch (ParseException e) { }
		return null;		
	}
	
	public static String sdf(Date d) {
		return sdf(d,"dd.MM.yyyy");
	}
	public static String sdf(Date d, String fmt) {
		SimpleDateFormat sdf = new SimpleDateFormat(fmt);
		return sdf.format(d);
	}
	
	
}
